<template>
  <div style="background:#f3f3f3">
    <header class="mint-header" style="font-size: 18px;">
      <div class="mint-header-button is-left">
        <button
          class="mint-button mint-button--default mint-button--normal"
          style="font-size: 15px;"
          @click="option"
        >
          <span class="mint-button-icon">
            <i class="mintui mintui-back" />
          </span>
          <label class="mint-button-text">返回</label>
        </button>
      </div>
      <h1 class="mint-header-title">添加出车记录</h1>
      <div class="mint-header-button is-right" />
    </header>
    <div style="height:40px" />
    <picker
      :values="carid"
      :picdata="carlist"
      class="rd_picker"
      style="margin-left:-8px;"
      pictitle="*车辆牌照"
      @getpicval="getpicval"
    />

    <mt-field v-model="usedetail" label="出车用途:" placeholder="输入出车用途" />
    <mt-field label="出车时间:" is-link>
      <span style="color:#888">{{ grantime }}</span>
    </mt-field>
    <mt-field label="行车地点:" is-link>
      <span style="color:#888;">{{ addressdetail }}</span>
    </mt-field>
    <mt-field v-model="perpor" label="同行人" placeholder="请输入同行人" />
    <!-- <uploadpic></uploadpic> -->
    <mt-button type="primary" style="width:100%;margin-top:20px" @click="gonuxt">确 定</mt-button>
    <div class="datePicker">
      <mt-datetime-picker
        ref="picker"
        :visible-item-count="5"
        type="datetime"
        year-format="{value} 年"
        month-format="{value} 月"
        date-format="{value} 日"
        hour-format="{value} 时"
        minute-format="{value} 分"
        @confirm="handleConfirm"
      />
    </div>
  </div>
</template>
<script>
import picker from '~/components/picker.vue'
import wx from 'weixin-js-sdk'
import vueJsonp from 'vue-jsonp'
import { formatDateMin } from '~/assets/formdate.js'
export default {
  components: {
    picker
  },
  layout: 'default2',
  data() {
    return {
      showamap: false,
      popupVisible22: false,
      adrword: '',
      isRouterAlive: false,
      popupVisible: false,
      equilist: [],
      userName: '',
      usedetail: '',
      city: '',
      dataList: [
        {
          flex: 1,
          values: [],
          className: 'slot1',
          textAlign: 'right'
        }
      ],
      htitle: '添加出车记录',
      ts: this.newStore(),
      grantime: '请选择出车时间',
      mapdata: {},
      lat: '',
      lng: '',
      carid: '',
      chouseval: '',
      chousname: [],
      chouseid: '',
      dateval: {},
      wxinfo: {
        appId: '',
        timestamp: '',
        nonceStr: '',
        signature: ''
      },
      perpor: '',
      cityname: '',
      addressdetail: '',
      carlist: []
    }
  },

  mounted() {
    console.log(this.$jsonp, '000000')
    this.chouseval = '请选择牌照'
    this.grantime = this.formatDate(new Date())
    this.getWxConfig()
    this.getcarlist()
  },
  activated() {
    // this.getWxConfig()
    // alert(1)
    //this.getcarlist()
  },

  methods: {
    getpicval(val) {
      this.carid = val.showid
    },
    getcarlist() {
      const req = {
        handle: '0E56125B90D2898A62E387C1CED62EC408B04B35BD44D675',
        query: ''
      }
      this.spost(this.ts, '/mainservlet', req).then(ts => {
        let a = []

        let item
        for (let index = 0; index < ts.d.data.operation1.length; index += 1) {
          let b = {}
          item = ts.d.data.operation1[index]
          b.showid = item.hash.carid
          b.showname = item.hash.carno
          a.push(b)
        }
        this.carlist = a
        console.log('11111')
      })
    },
    getWxConfig() {
      const { config } = window
      const res = {
        url: window.location.href
      }

      this.spost(this.ts, '/WeixinGetSignServlet', res).then(ts => {
        this.wxinfo = ts.d

        console.log(ts.d, '999')
        this.gowxconfig()
      })
    },
    //验证微信config
    gowxconfig() {
      //console.log(this.$jsonp, '000000')

      wx.config({
        debug: false,
        appId: this.wxinfo.appId,
        timestamp: this.wxinfo.timestamp,
        nonceStr: this.wxinfo.nonceStr,
        signature: this.wxinfo.signature,
        jsApiList: [
          // 所有要调用的 API 都要加到这个列表中
          'getLocation'
        ]
      })
      wx.ready(() => {
        wx.checkJsApi({
          jsApiList: ['getLocation'],

          success: res => {
            // alert(JSON.stringify(res))
            // console.log(res, '7777')
            // alert(JSON.stringify(res.checkResult.getLocation));
            if (res.checkResult.getLocation == false) {
              alert(
                '你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！'
              )
              return
            }
          }
        })
        wx.error(res => {
          console.log(res)
          window.location.reload()
        })
        wx.getLocation({
          success: res => {
            console.log(res, '6666')

            this.lat = res.latitude
            this.lng = res.longitude
            //console.log(this.hgdata)
            //console.log(this.lat, this.lng)
            //alert(this.lat)

            // this.getCurrentCity(this.lng, this.lat)
            // console.log(this.getCurrentCity(this.lng, this.lat))
            this.$jsonp('http://apis.map.qq.com/ws/geocoder/v1/', {
              location: `${res.latitude},${res.longitude}`,
              coord_type: 5,
              key: 'STLBZ-YCKCG-AGGQK-IV3HY-6CKP2-LGBPM',
              output: 'jsonp',
              callback: 'calllocation'
            }).then(json => {
              let { address, formatted_addresses } = json.result
              console.log(json.result, '66666')
              this.cityname = json.result.address_component.city
              this.addressdetail = address
              this.adrword = address
              //处理数据
            })
          },
          fail: function(res) {
            // alert('用户拒绝授权获取地理位置')
            this.wetoast.toast({
              title: '获取定位失败，请打开定位，重新进入！'
            })
            this.cityname = '无定位'
          }
        })
      })
    },
    handleConfirm2() {
      //this.chouseval = this.$refs.picker.getValues()[0]
      this.popupVisible22 = false
    },
    onDateChange(picker, values) {
      console.log(picker, 123456)
      console.log(values, 123)
      this.chouseval = values
      for (let k = 0; k < this.chousname.length; k++) {
        if (this.chouseval == this.chousname[k].carno) {
          this.chouseid = this.chousname[k].carid
        }
      }
    },
    option() {
      this.$router.go(-1)
    },
    addcarid() {
      const req = {
        handle: '0E56125B90D2898A62E387C1CED62EC408B04B35BD44D675',
        query: ''
      }
      this.spost(this.ts, '/mainservlet', req).then(ts => {
        let a = []
        let b = []
        for (let i = 0; i < ts.d.data.operation1.length; i++) {
          a.push(ts.d.data.operation1[i].hash.carno)
          b.push(ts.d.data.operation1[i].hash)
          //a[m] = { carid: ts.d.data.operation1[m].hash.carno }
        }
        this.dataList[0].values = a
        this.chousname = b
        console.log(this.chousname, 'wwwww')
      })
      this.popupVisible22 = true
    },
    addtime() {
      this.$refs.picker.open()
    },
    handleConfirm(data) {
      //console.log(data)
    },
    formatDate(date) {
      const y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours()
      h = h < 10 ? '0' + h : h
      let mi = date.getMinutes()
      mi = mi < 10 ? '0' + mi : mi
      return y + '-' + m + '-' + d + ' ' + h + ':' + mi + ':00'
    },
    getmapdata(data, city) {
      console.log(data, '00000')
      this.mapdata = data
      let lng = data.location.split(',')
      this.lat = lng[1]
      this.lng = lng[0]
      this.city = city
      //console.log(this.mapdata)
      this.adrword = data.name
      this.showamap = false
    },
    reload() {
      console.log('地图组件重新加载')

      this.isRouterAlive = false
      this.$nextTick(() => (this.isRouterAlive = true))
    },
    chooseadr() {
      this.reload()
      this.$nextTick(() => {
        this.showamap = true
      })
    },
    changeshow(data) {
      this.showamap1 = data
    },
    gonuxt() {
      if (this.carid == '' || this.carid == undefined) {
        this.$messagebox('提示', '请输入牌照')
        return
      }
      if (this.usedetail == '' || this.usedetail == undefined) {
        this.$messagebox('提示', '请输入出车用途')
        return
      }
      if (this.grantime == '请选择出车时间' || this.grantime == undefined) {
        this.$messagebox('提示', '请选择出车时间')
        return
      }
      if (this.adrword == '请选择出车地点' || this.adrword == undefined) {
        this.$messagebox('提示', '请选择出处地点')
        return
      }
      if (this.perpor == '请输入同行人' || this.perpor == undefined) {
        this.$messagebox('提示', '请输入同行人')
        return
      }
      this.$messagebox.confirm('是否确认添加').then(action => {
        const req = {
          handle: '0E56125B90D2898AB012A1AB3CBB9715DFA9FD06AD01858B',
          carid: this.carid,
          recordtime: this.grantime,
          usedetail: this.usedetail,
          lng: this.lng,
          lat: this.lat,
          useaddress: this.adrword,
          colperson: this.perpor
        }
        this.spost(this.ts, '/mainservlet', req).then(ts => {
          console.log(req, 'rewq')
          if (ts.d.sflag == 'success') {
            this.$messagebox('提示', '添加成功').then(action => {
              this.$router.push({
                name: 'carused',
                qery: {
                  name: '司机出车记录'
                }
              })
            })
          }
        })
      })
    }
  }
}
</script>
<style scoped>
.mint-cell-value .mint-field-core {
  text-align: right !important;
}
input .mint-field-core {
  text-align: right;
}
.picker-item {
  text-align: center !important;
}
.info-title {
  padding: 10px;
  color: #ccc;
  font-size: 16px;
}
html {
  background: #f3f3f3;
}
.equi-div {
  font-size: 12px;
  line-height: 20px;
  color: #969191;
}
.equi-shebei {
  display: inline-block;
  padding: 1px 10px;
  color: #fff !important;
  background: rgb(51, 51, 51);
}
.h3_equi {
  font-size: 16px;
  font-weight: 400;
  line-height: 40px;
}
.equi-span2 {
  width: calc(calc(100% / 2) - 10px);
}
.equi-div1 {
  font-size: 16px;
  line-height: 25px;
  /* margin: 0 10px; */
  /* border-bottom: 1px solid #ddd; */
  padding-bottom: 10px;
}
.equi-span {
  color: #35495e;
}
.equi-xq {
  line-height: 90px;
  /* padding-left: 20px; */
  color: #26a2ff;
  float: right;
  /* background: #ddd; */
  margin-top: 5px;
  width: 20%;
  text-align: center;
  border-left: 1px solid #ddd;
}
.equi-left {
  width: 100%;
  /* float: left; */
  padding-right: 0px;
  /* margin: 0 auto; */
  padding: 10px;
  background: #fff;
}
.mapcontent {
  width: 100%;
  height: 100%;
}
.mint-search {
  height: 7vh;
}
.mint-searchbar {
  background: #f3f3f3 !important;
}
</style>
